package com.wjw.cloud.common.exception;

import com.wjw.cloud.common.util.AjaxResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    private String defaultMessage = "系统出错，请与系统管理员联系!";

    @ExceptionHandler(Exception.class)
    public AjaxResponse handleException(final Throwable ex) {
        AjaxResponse ajaxResponse = new AjaxResponse();
        String msg = this.defaultMessage;
        if (ex instanceof BusinessException) {
            msg = ex.getMessage();
            if (msg == null || msg.equals("")) {
                msg = this.defaultMessage;
            }
        } else if (ex instanceof DataAccessException) {
            msg = ex.getMessage();
            if (msg == null || msg.equals("")) {
                msg = this.defaultMessage;
            }
        } else {
            msg = ex.getMessage();
            if (msg == null || msg.equals("")) {
                msg = ex.getClass().getName() + ": " + ex.getMessage();
            }
        }
        LOG.error(msg, ex);
        ajaxResponse.setErrorMsg(msg);
        return ajaxResponse;
    }

}